import { app, shell, BrowserWindow, ipcMain, Tray, Menu } from 'electron';
import { join } from 'path';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import icon from '../../resources/icon.png?asset';
import { currentChildren } from './children';

let mainWindow: BrowserWindow | null = null;
let tray: any = null;
const defaultSize = { width: 600, height: 300 };
function createWindow(): void {
  mainWindow = new BrowserWindow({
    width: defaultSize.width,
    height: defaultSize.height,
    show: false,
    transparent: true,
    autoHideMenuBar: true,
    titleBarStyle: 'hidden',
    ...(process.platform === 'linux' ? { icon } : { icon }),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  });

  mainWindow.on('ready-to-show', () => {
    mainWindow?.webContents.openDevTools({ mode: 'detach' });
    mainWindow?.show();
  });
  mainWindow?.webContents.on('did-finish-load', () => {
    console.log('did-finish-load');
  });

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url);
    return { action: 'deny' };
  });

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.violet-tool');

  // 托盘
  tray = new Tray(icon);
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '打开应用',
      click: () => {
        console.log('打开应用');
        mainWindow?.show();
      }
    },
    {
      label: '退出',
      click: () => {
        app.quit();
      }
    }
  ]);
  tray.setToolTip('Violet Tool');
  tray.setContextMenu(contextMenu);
  tray.on('click', () => {
    console.log('tray-click');
  });

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window);
  });

  let childrenWindow: any = null;
  ipcMain.on('children-window', (_: any, item: string) => {
    console.log('🚀 ~ app.whenReady ~ children-window:');
    mainWindow?.hide();
    const data = JSON.parse(item);
    childrenWindow = currentChildren(data.code);
    if (childrenWindow) {
      childrenWindow.open(data.path);
    } else {
      console.log('not found!');
    }
  });
  ipcMain.on('router-back', () => {
    console.log('🚀 ~ app.whenReady ~ router-back:');
    mainWindow?.show();
    childrenWindow?.close();
    childrenWindow = null;
  });
  ipcMain.on(
    'set-window-size',
    (_: any, item: { width?: number; height?: number }) => {
      console.log('🚀 ~ app.whenReady ~ set-window-size:');
      mainWindow?.hide();
      if (item.width && item.height) {
        mainWindow?.setSize(item.width, item.height);
      } else {
        const size = mainWindow?.getSize();
        if (
          defaultSize.width !== size?.[0] ||
          defaultSize.height !== size?.[1]
        ) {
          mainWindow?.setSize(defaultSize.width, defaultSize.height);
        }
      }
      mainWindow?.show();
    }
  );

  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
